package dao;

import bean.Users;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

public class UsersDao {
    public boolean insertUser(Users users){
//        if(isUserExists(users)){
//            return false;
//        }

        Connection conn = DBUtil.getConn();
        String sql="insert into users(tel,name,pwd,email,sex) values(?,?,?,?,?);";
        PreparedStatement ps=null;
        int rowsAffected=0;
        try {
            ps= conn.prepareStatement(sql);
            ps.setString(1,users.getTel());
            ps.setString(2,users.getName());
            ps.setString(3,users.getPwd());
            ps.setString(4,users.getEmail());
            ps.setString(5,users.getSex());
            rowsAffected=ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.closeDBResource(null,ps,conn);
        }
        return rowsAffected==1;
    }
    public boolean isUserExists(Users users){
        Connection connection=DBUtil.getConn();
        String sql="SELECT COUNT(*) FROM users WHERE name = ?";
        PreparedStatement ps=null;
        ResultSet rs=null;
        int count=0;
        try{
            ps=connection.prepareStatement(sql);
            ps.setString(1,users.getName());
            rs= ps.executeQuery();
            if(rs.next()){
                count=rs.getInt(1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.closeDBResource(rs,ps,connection);
        }
        return count==1;
    }
    public void selectForLogin(Users users){
        Connection connection= DBUtil.getConn();
        String sql="select * from users where name=? and pwd=?";
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps=connection.prepareStatement(sql);
            ps.setString(1,users.getName());
            ps.setString(2,users.getPwd());
            rs=ps.executeQuery();
            while (rs.next()){
                int id=rs.getInt(1);
                String tel=rs.getString("tel");
                String username=rs.getString(3);
                String pwd=rs.getString(4);
                String email=rs.getString("email");
                String sex=rs.getString("sex");
                LocalDateTime createTimeValue=rs.getTimestamp("create_time").toLocalDateTime();


                users.setId(id);
                users.setTel(tel);
                users.setEmail(email);
                users.setSex(sex);
                users.setCreateTime(createTimeValue);

                System.out.println(users);
            }
        } catch (SQLException e) {
            users.setId(-1);
//            e.printStackTrace();
//            throw new RuntimeException(e);
        }finally {
            DBUtil.closeDBResource(rs,ps,connection);
        }
    }
}
